package in.muton.edushare.components.tasks.electives.allotment;

import in.muton.edushare.jobs.SemesterChangeJob;

import java.util.List;

import org.apache.wicket.model.IModel;

import com.edushare.common.dao.AcademicYearModelDAO;
import com.edushare.common.dao.CourseInstancesDAO;
import com.edushare.common.dao.CoursesDAO;
import com.edushare.common.dao.academics.grades.InternalGrades;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.CourseInstances;
import com.edushare.common.vo.Courses;
import com.edushare.common.vo.Enrolments;
import com.edushare.common.vo.Universities;

public class ChangeSem {

	public ChangeSem(IModel<Universities> univModel) {
		this.univModel = univModel;
	}

	public void changeSemUserCommand(ORMInterface orm) {
		SemesterChangeJob.log.debug("In changeSemUserCommand for" + univModel.getObject().getUniversityName());
		CoursesDAO bDAO = new CoursesDAO(orm);
		if(univModel.getObject().getElectiveSelectionTime() == Universities.UNIV_SCHEDULE_SEMESTER_CHANGE){
			SemesterChangeJob.log.debug("UNIV_SCHEDULE_SEMESTER_CHANGE for" + univModel.getObject().getUniversityName());
			List<Courses> courseList = new CoursesDAO(orm).getUnivCourses(univModel.getObject());
			for(Courses c:courseList){
				CourseInstances cinst = new CourseInstancesDAO(orm).getActiveInst(c);
				if(cinst != null){
					List<Enrolments> eList = cinst.getEnrolmentList();
					for(Enrolments e:eList){
						if(e.getEnrolmentType() == Enrolments.STUDENT ||
								e.getEnrolmentType() == Enrolments.OBSERVER){
							new InternalGrades(orm).recalculateCGPA(cinst,e.getUser());
						}
					}
				}
			}
			bDAO.closeAllCoures(univModel.getObject());
			new AcademicYearModelDAO(orm, univModel.getObject()).incrementSemester();
			new MandatoryCourseAllot(univModel).allocateCoursesSem(orm);
			univModel.getObject().setElectiveSelectionTime(Universities.UNIV_ALLOW_ELECTIVE_SELECTION);
		}
		orm.commitAllChanges();
	}

	public void setElectiveCourses(ORMInterface orm) {
		new ElectiveCourseAllot(univModel).allotElectiveCourses(orm);
	}

	private IModel<Universities> univModel = null;
}
